<?php
namespace app\bancard\controller;

use think\Db;
use think\facade\Cache;
use app\common\validate\AttendancesettingValidate as AttendanceValidate;
use app\bancard\model\AttendanceSettings as AttendanceModel;

class Attendanceteacher extends Common
{

    protected $attendance_status;
    protected $setting_attendance_count;    //考勤类型次数 默认10
    protected $setting_school_type_where;  //教师考勤控制器中需要通用的条件 学校、教师

    public function __construct()
    {
        parent::__construct();
        $this->setting_attendance_count = 10;
        $this->setting_school_type_where = [
            'school_id' => session('schoolInfo.id'),
            'type' => 1
        ];
        $this->attendance_status = [0 => '', 1 => '正常', 2 => '迟到', 3 => '早退', 4 => '缺卡', 5 => '请假'];

    }

    //教师考勤首页
    public function index()
    {
        return $this->fetch();
    }

    //教师考勤列表
    public function lists()
    {

        $ntitle = request()->param('keywords');
        $title = isset($ntitle) ? $ntitle : '';
        $limit = request()->param('limit');
        $offset = request()->param('offset');
        $start = ($offset - 1) * $limit;

        $school_where = ['a.school_id' => session('schoolInfo.id')];
        if ($title) {

            $teacher_info = $this->getTeacherId($title);

            $teacher_ids = $teacher_info['data'];

            $map[] = ['teacher_id', 'in', $teacher_ids];

            $count = db('attendance_teacher_log')->alias('a')->where($school_where)->where($map)->count();
            $result = db('attendance_teacher_log')->alias('a')->leftjoin('attendance_settings b', 'a.event_id=b.id')->where($school_where)->where($map)->limit($start, $limit)->order('a.id desc')->select();


        } else {
            $count = db('attendance_teacher_log')->alias('a')->where($school_where)->count();
            $result = db('attendance_teacher_log')->alias('a')->leftjoin('attendance_settings b', 'a.event_id=b.id')->where($school_where)->limit($start, $limit)->order('a.id desc')->select();

        }
        
        if (empty($result)) {
            return showTable(0, 'OK', $count, $result, 200);
        }
        $teacher_ids = array_column($result,'teacher_id');
        
        //取得教师信息
        $ndata = $this->getTeacher($teacher_ids);
        $teachers = $ndata['data'];
        

        if(empty($teachers)){
            return showTable(0, 'OK', 0, $result, 200);
        }
        
        foreach ($result as $key => $value) {
            if(isset($teachers[$value['teacher_id']])){
                $result[$key]['teacher_name'] = $teachers[$value['teacher_id']]['name'];
                $result[$key]['teacher_mobile'] = $teachers[$value['teacher_id']]['mobile'];
            }
        }
        return showTable(0, 'OK', $count, $result, 200);
    }

    //考勤设置列表首页
    public function attendance()
    {

        return $this->fetch();

    }


    //教师考勤设置列表
    public function settingLists()
    {
        $count = db('attendance_settings')->where(['status'=>1])->where($this->setting_school_type_where)->count();
        $result = db('attendance_settings')->where(['status'=>1])->where($this->setting_school_type_where)->order('start_time asc,end_time asc')->select();

        return showTable(0, 'OK', $count, $result, 200);
    }

    //检查操作是否正确
    private function checkAttenHandle($start_time, $end_time, $type, $grade_id, $id = 0,$att_range = 0)
    {
        $where = ['school_id' => session('schoolInfo.id'), 'type' => $type, 'grade_id' => $grade_id,'status'=>1];

        $param_start_time = $start_time;

        $param_end_time = $end_time;
        //时间先后判断放在最前面，以适应编辑
        if ($param_start_time > $param_end_time) {
            return ['code' => 1002];

        }

        //编辑的时候，排除和自己的比较
        if (!empty($id)) {
            $where = [
                ['school_id', '=', session('schoolInfo.id')],
                ['type', '=', $type],
                ['grade_id', '=', $grade_id],
                ['id', '<>', $id],
                ['status', '=', 1],
            ];
        }

        $result = db('attendance_settings')
            ->where($where)
            ->where(function ($query) use ($start_time, $end_time) {
                $query->where(function ($q) use ($start_time) {
                    $q->where([
                        ['start_time', '<=', $start_time],
                        ['', 'exp', Db::raw('DATE_ADD(end_time,INTERVAL att_range MINUTE) >= "'. $start_time . '"')]
                    ]);
                })->whereOr(function ($q) use ($end_time) {
                    $q->where([
                        ['start_time', '<=', $end_time],
                        ['', 'exp', Db::raw('DATE_ADD(end_time,INTERVAL att_range MINUTE) >= "'. $end_time . '"')]
                    ]);
                });
            })->find();


        if (!empty($result)) {
            return ['code' => 1003, 'start_time' => $result['start_time'], 'end_time' => $result['end_time']];

        }

    }


    //添加考勤设置
    public function add()
    {

        if (request()->isPost()) {

            $data = request()->param();

            $data['type'] = isset($data['type']) ? $data['type'] : 1;
            $data['grade_id'] = isset($data['grade_id']) ? $data['grade_id'] : 0;
            $data['is_range'] = isset($data['is_range']) ? $data['is_range'] : 0;
            $data['created_at'] = date('Y-m-d H:i:s', time());
            $data['user_id'] = session('admin.id');
            $data['school_id'] = session('schoolInfo.id');
            $data['status'] = 1;
            $validate = new AttendanceValidate;
            if (!$validate->scene('add')->check($data)) {
                return show(0, $validate->getError(), 0, 200);
            } else {

                $where = ['school_id' => session('schoolInfo.id'), 'type' => $data['type'], 'grade_id' => $data['grade_id']];


                $count = db('attendance_settings')->where($where)->count();
                if ($count >= $this->setting_attendance_count) {
                    return show(0, '添加失败！只可以添加' . $this->setting_attendance_count . '次考勤。', 0, 200);
                }

                //检查操作是否合适
                $is_res = $this->checkAttenHandle($data['start_time'], $data['end_time'], $data['type'], $data['grade_id'],0,$data['att_range']);

                if ($is_res['code'] == 1002) {
                    return show(0, '添加失败！开始时间不能大于结束时间', 0, 200);

                } elseif ($is_res['code'] == 1003) {
                    return show(0, '添加失败！考勤时间重复，已存在时段' . "\r\n" . $is_res['start_time'] . '--' . $is_res['end_time'], 0, 200);

                }

                Cache::clear('attendance_settings');
                $rest = (new AttendanceModel())->strict(false)->insert($data);

                return show(1, '添加成功', $rest, 200);
            }
        }

        return $this->fetch();
    }

    //编辑考勤设置
    public function edit()
    {

        if (request()->isPost()) {
            $data = request()->param();

            $data['user_id'] = session('admin.id');
            $data['school_id'] = session('schoolInfo.id');
            $validate = new AttendanceValidate;
            if (!$validate->scene('edit')->check($data)) {
                return show(0, $validate->getError(), 0, 200);
            } else {

                $data['type'] = isset($data['type']) ? $data['type'] : 1;
                $data['grade_id'] = isset($data['grade_id']) ? $data['grade_id'] : 0;

                //检查操作是否合适
                $is_res = $this->checkAttenHandle($data['start_time'], $data['end_time'], $data['type'], $data['grade_id'], $data['id'],$data['att_range']);

                if ($is_res['code'] == 1002) {
                    return show(0, '编辑失败！开始时间不能大于结束时间', 0, 200);

                } elseif ($is_res['code'] == 1003) {
                    return show(0, '编辑失败！考勤时间重复，已存在时段' . "\r\n" . $is_res['start_time'] . '--' . $is_res['end_time'], 0, 200);

                }


                Cache::clear('attendance_settings');


                isset($data['is_range']) ? ($data['is_range'] = $data['is_range']) : ($data['is_range'] = 0);


                $rest = (new AttendanceModel())->strict(false)->where('id', $data['id'])->update($data);

                return show(1, '修改成功', $rest, 200);
            }
        }
        $data = request()->param();
        $result = db('attendance_settings')->where('id', '=', $data['id'])->find();

        $this->assign('result', $result);
        return $this->fetch();
    }

    //删除考勤设置，单个、批量通用
    public function delete()
    {
        Cache::clear('attendance_settings');
        $data = request()->param();
        $result = db('attendance_settings')->whereIn('id',$data['ids'])->update(['status'=>0]);
        return show(1, '删除成功', $result, 200);
    }


}